<?php

namespace app\helper;

/**
 * 图片处理
 */
class Image
{
    //图片类型
    private $type;
    //实际宽度
    private $width;
    //实际高度
    private $height;
    //实际比例
    private $radio;
    //源图象地址
    private $cut;
    //临时创建的图象
    private $im;
    
    //初始化图象
    public function fetch(string $src)
    {
        //图片的类型
        $this->type = strtolower(substr(strrchr($src,"."),1));
        if ($this->type=="jpg" || $this->type=="jpeg") {
          $this->im = imagecreatefromjpeg($src);
        } elseif ($this->type=="gif") {
          $this->im = imagecreatefromgif($src);
        } elseif ($this->type=="png") {
          $this->im = imagecreatefrompng($src);
        }
        $this->width = imagesx($this->im);
        $this->height = imagesy($this->im);
        $this->radio = $this->width/$this->height;
        return $this;
    }
    // 剪裁
    public function cut(int $w, int $h){
        $this->cut = [$w, $h, $this->width, $this->height];
        $ratio = $w/$h;
        if($ratio>=$this->radio){
            $this->cut[2] = $this->height * $this->radio;
        } else {
            $this->cut[3] = $this->width / $this->radio;
        }
        return $this;
    }
    // 缩放
    public function scale(int $w = 320, int $h = 320){
        $this->cut = [$w, $h, $this->width, $this->height];
        $ratio = $w/$h;

        if($ratio>=$this->radio) {
            $this->cut[1] = $w/$ratio;
        } else {
            $this->cut[0] = $h*$ratio;
        }

        return $this;
    }
    public function save(string $dst)
    {
        $img = imagecreatetruecolor($this->cut[0], $this->cut[1]);
        imagecopyresampled($img, $this->im, 0, 0, 0, 0, $this->cut[0], $this->cut[1], $this->cut[2], $this->cut[3]);
        ImageJpeg($img, $dst);
        //生成图象
        ImageDestroy($this->im);
        // return $this;
    }
}
